import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    ScrollView,
    TouchableOpacity,
    TextInput,
    ListView,
    Modal,
    Animated,
    Platform,
    TouchableNativeFeedback,
    Alert
} from 'react-native';
import ImageWrapper from '../components/ImageWrapper';
import StorageUser from '../lib/plugins/StorageUser';
import NavigationBar from '../components/NavigationBar';
import shopService from '../lib/services/shopService';
import bankData from '../json/bankData';
var Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');
export default class BankCard extends Component{
    constructor(props) {
        super(props);
        this.timer = null;
        this.token = '';
        this.userId = '';
        this.firstArr = [];
        this.state = {
            userName:'',
            bankName:'卡类型',
            bankNum:'',
            bankAddress:'',
            phone:'',
        };
    }
    componentDidMount() {
        var $this = this;
        StorageUser._getUser()
            .then(data=>{
                if(data.token){
                    $this.token = data.token;
                }
                if(data.userId){
                    $this.userId = data.userId;
                }                
            }).catch(err=> {
                console.log(err)
            });
    }
    
    render(){
        return (
            <View style={styles.container}>
                <NavigationBar 
                    leftIcon={'left'} 
                    titleText={'绑定银行卡'} 
                    leftPress={()=>this.goBack()}/>
                <ScrollView>
                    <View style={styles.box}>
                        <InputItem onChangeText={(text)=>this.getUserName(text)} style={styles.bottomBorder} title={'持卡人'} placeholder={'请输入持卡人真实姓名'}/>
                        <InputItem onChangeText={(tetx)=>this.getBankNum(text)} onChangeText={(text)=>this.getBankName(text)} style={styles.bottomBorder} title={'卡号'} placeholder={'请输入卡号'}/>
                        <View style={[styles.itemBox,styles.bottomBorder]}>
                            <View style={styles.titleBox}>
                                <Text style={styles.text}>卡类型</Text>
                            </View>
                            <View style={{flex:1}}>
                                <Text style={{color:'#333'}}>{this.state.bankName}</Text>
                            </View>
                        </View>
                        <InputItem onChangeText={(text)=>this.getBankAddress(text)} style={styles.bottomBorder} title={'开户行'} placeholder={'请输入开户行'}/>
                        <InputItem onChangeText={(text)=>this.getPhone(text)} title={'手机号'} placeholder={'请输入手机号'}/>
                    </View>
                    <View style={styles.submitBtn}>
                        <TouchableOpacity onPress={()=>this.addBankCard()}>
                            <View style={{backgroundColor:'rgb(79,145,237)',height:40,alignItems:'center',justifyContent:'center',borderRadius:3,width:width*2/3}}>
                                <Text style={{color:'#fff',fontSize:16}}>确 定</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                </ScrollView>
            </View>
        )
    }
    getBankName(text){
        // alert(JSON.stringify(bankData));
        var len = bankData.length;
        var num = text.replace(/^\s$/g,'');
        var length = num.length;
        var bankName = '卡类型';
        if(length==6){
            for(var i=0;i<len;i++){
                if(num==bankData[i].bin.slice(0,6)){
                    // alert(bankData[i].bankName);
                    // bankName = bankData[i].bankName;
                    // this.setState({
                    //     bankName:bankName,
                    // })
                    this.firstArr.push(bankData[i]);
                }
            }

        }
        var firstLen = this.firstArr.length;
        if(firstLen==1){
            this.setState({
                bankName:this.firstArr[0].bankName,
            })
        }else if(length>6 && length<11){
            alert
            for(var i=0;i<firstLen;i++){
                if(num==this.firstArr[i].bin){
                    this.setState({
                        bankName:this.firstArr[i].bankName,
                    })
                    break;
                }
            }
        }else if(length<6){
            this.firstArr = [];
            this.setState({
                bankName:bankName,
            })
        }
        this.setState({
            bankNum:text,
        })
        
    }
    // 返回按钮
    goBack(){
        clearTimeout(this.timer);
        this.props.navigation.goBack();
    }
    // 获取持卡人姓名
    getUserName(text){
        this.setState({
            userName:text
        })
    }
    // 获取银行卡号
    getBankNum(text){
        this.setState({
            bankNum:text
        })
    }
    // 获取开户行
    getBankAddress(text){
        this.setState({
            bankAddress:text
        })
    }
    // 获取手机号
    getPhone(text){
        this.setState({
            phone:text
        })
    }
    // 添加银行卡
    addBankCard(){
        var $this = this;
        var userName = this.state.userName.replace(/^\s$/g,'');
        var bankNum = this.state.bankNum.replace(/^\s$/g,'');
        var bankAddress = this.state.bankAddress.replace(/^\s$/g,'');
        var phone = this.state.phone.replace(/^\s$/g,'');
        var staturs = /^1[3578][0-9]{9}$/.test(phone);
        if(userName==''){
            alert('请填写持卡人姓名！');
            return;
        }else if(this.state.bankName=='卡类型' || this.state.bankName==''){
            alert('无法识别银行卡号！');
            return;
        }else if(bankAddress==''){
            alert('请填写开户行！');
            return;
        }else if(!staturs){
            alert('请填写正确的手机号！');
            return;
        }else{
            shopService.userBindBankCard(function(data){
                alert(JSON.stringify(data));
                if(data.code==10000){
                    Alert.alert(
                        '提示信息',
                        '添加成功',
                        [{text: '确定', onPress: () => {$this.props.navigation.state.params.upData();$this.goBack()}}])
                }
            },userName,bankNum,this.state.bankName,bankAddress,phone,$this.userId,$this.token)
        }
    }


}
class InputItem extends Component{
    render(){
        return(
            <View style={[styles.itemBox,this.props.style]}>
                <View style={styles.titleBox}>
                    <Text style={styles.text}>{this.props.title}</Text>
                </View>
                <View style={{flex:1}}>
                    <TextInput 
                        onChangeText={this.props.onChangeText}
                        placeholder={this.props.placeholder}
                        style={styles.input}
                        underlineColorAndroid="transparent" 
                        selectionColor={'#aaa'}/>
                </View>
            </View>
        )
    }
}
const styles = StyleSheet.create({
    container:{
        flex:1,
        backgroundColor:'#EFEFF4',
        ...Platform.select({
            ios: {
                marginTop: 20
            },
            android: {
                marginTop:0
            },
        }),
    },
    box:{
        backgroundColor:'#fff',
        paddingLeft:10,
        borderTopWidth:1,
        borderTopColor:'#ccc',
        borderBottomWidth:1,
        borderBottomColor:'#ccc',
    },
    itemBox:{
        flexDirection:'row',
        height:50,
        alignItems:'center',
    },
    titleBox:{
        width:60,
        alignItems:'flex-start'
    },
    text:{
        fontSize:16,
        color:'#333'
    },
    input:{
        flex:1,

    },
    bottomBorder:{
        borderBottomWidth:1,
        borderBottomColor:'#ccc'
    },
    button:{
        width:80,
        backgroundColor:'rgb(79,145,237)',
        height:30,
        alignItems:'center',
        justifyContent:'center',
        borderRadius:3
    },
    submitBtn:{
        marginTop:80,
        alignItems:'center'
    }

});